#!/usr/bin/env python

import os

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import users
from models.library import Library
from lib.recaptcha.client import captcha
from models.setting import Setting
import uuid
from lib import isbn

# This controller handles the
# generation of the front page.

class MainHandler(webapp.RequestHandler):
    def get(self):
    
        # We are using the template module to output the page.
    
        path = os.path.join(os.path.dirname(__file__), '../views' ,'search.html')
        self.response.out.write(
        
            # The render method takes the path to a html template,
            # and a dictionary of key/value pairs that will be
            # embedded in the page.
            
            template.render( path, {
                "admin_user": users.is_current_user_admin()
        }))


class LibraryContributeHandler(webapp.RequestHandler):
    def get(self):
    
        # We are using the template module to output the page.
        disabled_contributions = Setting.get("disabled_contributions", False)
        data = {
            "admin_user": users.is_current_user_admin(),
            "disabled_contributions" : disabled_contributions,
            }
        debug = ''
        error = None
        preview = False

        if not disabled_contributions:

            try:
            
                for field in ["title", "link", "have", "dont"]:
                    data[field] = self.request.get(field)
                
                if not data["title"] and not data["link"]:
                    data["title"] = "DC - Library of Congress"
                    data["link"] = "http://www.loc.gov/search/?q=#{ISBN}&fa=digitized:false"
                    data["missing"] = "We did not find any matches for this search."
                    data["have"] = "0321337220"
                    data["dont"] = "0373691122"
                
                else:
                
                    if self.request.get("missing"):
                        data["missing"] = self.request.get("missing")
                    else:
                        data["match_isbn"] = True
                
                data["name"] = uuid.uuid4().hex
                data["is_community"] = True

                preview = self.request.get('preview')
                save = self.request.get('save')
            
                if save:
        
                    preview = True
        
                    challenge = self.request.get('recaptcha_challenge_field')
                    response  = self.request.get('recaptcha_response_field')
                    remoteip  = self.request.environ['REMOTE_ADDR']
                    
                    cResponse = captcha.submit(
                                 challenge,
                                 response,
                                 Setting.get("recaptcha_private", ''),
                                 remoteip)
                    if not cResponse.is_valid:
                        raise Exception("reCaptcha verification failed (" + cResponse.error_code + ")")
        
                    existingLib = Library.find(data["title"])
                                    
                    if existingLib:
                        raise Exception("Another library with this title already exists!")
                        
                    if not isbn.isValid(data["have"]):
                        raise Exception("Existing Book: '%s' is not a valid ISBN!" % (data["have"]))
                    if not isbn.isValid(data["dont"]):
                        raise Exception("Missing Book: '%s' is not a valid ISBN!" % (data["dont"]))
        
                    lib = Library.create(data)
                        
                    problems = lib.validate()
                    if problems:
                        raise Exception("Library didn't validate: " + problems)
                        
                    lib.remote_ip = remoteip
                    
                    lib.put()
                    
                    data["success"] = "Library '%s' was successfuly saved.\nThank you for your contribution." % (data["title"])
                
                if preview:
                    lib = Library.create(data)
                    data["haveUrl"] = lib.siteUrl(data["have"])
                    data["dontUrl"] = lib.siteUrl(data["dont"])
                else:
                    data["library_count"] = Library.count_all()
        
            except Exception, ex:
                error = "%s" % (ex,)

        if preview:
            data["captcha_html"] = captcha.displayhtml(
                public_key = Setting.get("recaptcha_public", '')
            )
            path = os.path.join(os.path.dirname(__file__), '../views' ,  'contribute-preview.html')
        else:
            path = os.path.join(os.path.dirname(__file__), '../views' ,  'contribute.html')
        
        data["debug"] = debug

        data["error"] = error
        data["can_submit"] = (not error) or error.startswith("reCaptcha ")
        
        self.response.out.write(
        
            # The render method takes the path to a html template,
            # and a dictionary of key/value pairs that will be
            # embedded in the page.
            
            template.render( path, data))

    def post(self):
        self.get()
